package com.brkj.test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.view.KeyEvent;
import com.brkj.util.ActivityStackControlUtil;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import com.brkj.httpInterface.BaseAjaxParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.brkj.main.R;
import com.brkj.test.model.DS_Exam;
import com.brkj.httpInterface.HttpInterface.HIF_GetExamList;
import com.brkj.util.ConstAnts;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.MyApplication;
import com.brkj.util.view.BaseActionBarActivity;
import com.brkj.util.view.BaseActionBarItem.itemClick;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.PullListView;
import com.dgl.sdk.util.DBStore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ExamActivity extends BaseActionBarActivity{

	@ViewInject(id=R.id.examListView) PullListView examListView;
	@ViewInject(id=R.id.noData,click="click_noData") TextView noData;
	
	private List<DS_Exam> examList =  new ArrayList<DS_Exam>();
    private List<DS_Exam> offlineExamList = new ArrayList<DS_Exam>();
	protected ExamAdapter adapter;
	private BroadcastReceiver br;
    private long exitTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_exam);

        setRightBtnBackgroundAndListener(R.drawable.ico_search, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(ExamSearchActivity.class);
            }
        });

		addTitleButtonItem("题库学习", new itemClick() {
			
			@Override
			public void onClick() {
                if(examList.size()==0){
                    getExam();
                }else{
                    fillView(examList, false);
                }

			}
		});

		addTitleButtonItem("离线题库", new itemClick() {
			
			@Override
			public void onClick() {

				
				fillView(offlineExamList, true);

			}
		});

        offlineExamList = DBStore.readAll(DS_Exam.class, ConstAnts.DB_TABLE_OFFLINE_QUES_LIST);

		getExam();
		
		examListView.setonGetMoreListener(new PullListView.OnGetMoreListener() {
            @Override
            public void onGetMore() {
                getMoreExam();
            }
        });
		
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("com.brkj.examHaveDoneChanged");

		br = new BroadcastReceiver(){

			@Override
			public void onReceive(Context context, Intent intent) {
				adapter.notifyDataSetInvalidated();
			}
		};
		
		registerReceiver(br, myIntentFilter);
		
	}

	public void click_noData(View v){
		getExam();
	}
	
	private void getExam() {
		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HIF_GetExamList.params.UserID, MyApplication.myUserID);
		params.put(HIF_GetExamList.params.ExamPaperID, "0");

		FinalHttp fh = new FinalHttp();
		fh.post(HIF_GetExamList.address, params, new MyAjaxCallBack<Object>(this) {


			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Exam>>(){}.getType();
				examList = gson.fromJson((String)t, listType);
				
				fillView(examList, false);

			}
			
		});
		
	}


    private void getMoreExam() {
        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HIF_GetExamList.params.UserID, MyApplication.myUserID);
        params.put(HIF_GetExamList.params.ExamPaperID,
                Integer.toString(examList.get(examList.size()-1).getExamPaperID()));

        FinalHttp fh = new FinalHttp();
        fh.post(HIF_GetExamList.address, params, new MyAjaxCallBack<Object>(this) {


            @Override
            public void onSuccess(Object t) {
                // TODO Auto-generated method stub
                super.onSuccess(t);

                Gson gson = new Gson();
                Type listType = new TypeToken<List<DS_Exam>>(){}.getType();
                List<DS_Exam> moreList = gson.fromJson((String)t, listType);
                if(moreList!=null){
                    examList.addAll(moreList);
                    adapter.notifyDataSetChanged();
                }

            }

        });

    }

	private void fillView(List<DS_Exam> list, boolean isOffLineList){
		if((list != null) &&(list.size()>0)){

            mergeData(list);

			adapter = new ExamAdapter(ExamActivity.this, list, isOffLineList);
			examListView.setAdapter(adapter);

			examListView.setVisibility(View.VISIBLE);
			noData.setVisibility(View.GONE);
		}else{
			examListView.setVisibility(View.GONE);
			noData.setVisibility(View.VISIBLE);
		}
	}

    /**
     * 合并一些本地的数据
     * @param list
     */
    private void mergeData(List<DS_Exam> list) {

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(DS_Exam offlineExam:offlineExamList){
            map.put(offlineExam.getExamPaperID(), offlineExam.getExamPaperID());
        }

        for(DS_Exam exam:list){
            if(map.containsKey(exam.getExamPaperID())){
                exam.setDownload(true);
            }
        }
    }


    @Override
	public void finish() {
		super.finish();
		unregisterReceiver(br);
	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {
            if((System.currentTimeMillis() - exitTime) > 2000){
                showToast("再按一次退出掌上学苑 ");
                exitTime = System.currentTimeMillis();
            } else {
                ActivityStackControlUtil.finishProgram();
            }
        }

        return true;
    }
}
